package work.chief.service.impl;

import work.chief.dao.ProductDao;
import work.chief.dao.TrolleyDao;
import work.chief.dao.impl.ProductDaoImpl;
import work.chief.dao.impl.TrolleyDaoImpl;
import work.chief.entity.Product;
import work.chief.entity.Trolley;
import work.chief.service.TrolleyService;

import java.util.List;

public class TrolleyServiceImpl implements TrolleyService {
    private TrolleyDao trolleyDao=new TrolleyDaoImpl();
    private ProductDao productDao = new ProductDaoImpl();


    @Override
    public int addTrolley(Trolley trolley) {

        int uid=trolley.getUid();
        int pid=trolley.getPid();
        int number=trolley.getNumber();
        int num=-1;
        //根据uid，pid参数查找数据库
        Trolley trolley1 = trolleyDao.selectByTidAndUid(uid, pid);
        if (trolley1==null){    //条件：没有加入过购物车
            Trolley trolley2=new Trolley(); //构建一个新对象
            trolley2.setUid(uid);
            trolley2.setPid(pid);
            trolley2.setNumber(number);
            num=trolleyDao.addTrolley(trolley2); //插入购物车trolley2到数据库，并返回值到num
        }else {
            //trolley1.setNumber(trolley1.getNumber()+number);    //更新商品数量
            num=trolleyDao.updateByUidAndPid(uid,pid,trolley1.getNumber()+number); //选中uid，pid，将更新后的商品数量更新到服务器中
        }
        return num; //返回更新结果
    }

    @Override
    public Integer selectTrolleyCount(int uid) {
        return trolleyDao.selectTrolleyCount(uid);
    }

    @Override
    public List<Trolley> selectAllTrolley(int uid) {
        List<Trolley> trolleyList = trolleyDao.selectAllTrolley(uid);

        //遍历trolleyList
        for (Trolley t:trolleyList){
            //根据pid获取product
            Product product = productDao.selectByPid(t.getPid());
            //将获取到的product赋给t.product
            t.setProduct(product);
        }
        return trolleyList;
    }

    @Override
    public int deleteOrAll(String str) {
        int num=-1;
        if (str.contains(",")){
            num=trolleyDao.deleteByTids(str);   //批量删除
        }else {
            num=trolleyDao.deleteByTid(Integer.parseInt(str));  //单个删除
        }
        return num;
    }

    @Override
    public Trolley selectByTid(int tid) {
        return trolleyDao.selectByTid(tid);
    }
}
